extends Node

var players=[]
var enemys=[]
onready var cardSystem=$CardSystem
onready var cam=$Cam
onready var battleGroud=$BattleGroud
onready var turnEndButton=$EndButton
onready var points=$Points

var donghuaList=[]
var donghuaPlayer
var isPlaying=false #是否 动画播放器是不是在播放 当动画播放器不在播放并且动画列表为空时才算播放完了
var turnControl #回合控制

func _ready():
	
	#初始化数据
	randomize()
	Global.Battle=self
	#初始化动画播放器
	donghuaPlayer=load("res://DongHuaPlayer/DongHuaPlayer.gd").new()
	donghuaPlayer.connect("complete",self,"onDonghuaComplete")
	#初始化回合控制器
	turnControl=load("res://Logic/TurnControl.gd").new()
	#初始化其他
	turnEndButton.disabled=true
	
	#初始化角色
	#友军
	for i in range(3):
		var chess=load("res://Model/PlayerChess.gd").new()
		chess.loadData(ChessData.getData(i))
		addChess(chess,i)
	#敌人
	for i in range(3):
		var chess=load("res://Model/EnemyChess.gd").new()
		chess.loadData(ChessData.getData(100+i))
		addChess(chess,10+i)
	#初始化卡组
	var cards=[]
	for chess in players:
		for card in chess.cards:
			cards.append(card)
	#初始化卡牌系统
	cardSystem.start(cards,3,5)
	#执行游戏流程
	turnControl.execute()
	
	
	
	
	
	
func addChess(chess,posNumber):
	#添加模型
	match chess.align:
		0:
			players.append(chess)
		1:
			enemys.append(chess)
	#添加view
	var view=load("res://View/ChessView.tscn").instance()
	battleGroud.get_node(String(posNumber)).add_child(view)
	#view.position=battleGroud.get_node(String(posNumber)).position
	
	view.loadChess(chess)
	#添加链接
	Map.addM2V(chess,view)
	
func appendDonghua(donghua):
#	if !isPlaying:
#		donghuaPlayer.play(donghua)
#		isPlaying=true
#	else:
#		donghuaList.append(donghua)
	donghuaList.append(donghua)
	pass
func onDonghuaComplete():
	isPlaying=false
	pass
	
func _physics_process(delta):
	#检查并播放队列中的动画
	if !isPlaying && donghuaList.size()>0:
		var donghua=donghuaList.pop_front()
		isPlaying=true
		donghuaPlayer.play(donghua)
	pass
	#调用turncontorl的process
	turnControl.process()
	
func removeChess(chess):
	match chess.align:
		0:
			players.erase(chess)
			#移除玩家的卡牌
			cardSystem.exceptChessCard(chess)
		1:
			enemys.erase(chess)
			
#敌人行动
func enemyAct():
	var dh=[0]
	for enemy in enemys:
		var player=players[int(rand_range(0,players.size()))]
		if randf()<0.5:
			CardAction.blow(dh,enemy,player)
		else:
			CardAction.doubleAttack(dh,enemy,player)
	appendDonghua(dh)
	pass
#-------回合跳转函数----
#玩家回合结束，等待动画播放完，之后进入敌人回合
#func playerTurnBegin():
#	var dh=[0]
#	for player in players:
#		var a=player.armor/2
#		BaseAction.setProperty(dh,player,"armor",a)
#	turnEndButton.disabled=false
#	cardSystem.turnBegin()
#	turnState=0
#
#	appendDonghua(dh)
#	pass
#func playerTurnEnd():
#	cardSystem.playerTurnEnd()
#	turnEndButton.disabled=true
#	turnState=1
#	pass
##敌人回合开始
#func enemyTurnBegin():
#	turnState=2
#	enemyAct()
#	enemyTurnEnd()
#func enemyTurnEnd():
#	turnState=3
#	pass


func _on_EndButton_pressed():
	#按下回合结束按钮
	turnControl.onPlayerTurnEndButton()
	pass # replace with function body
